<template>
    <u-upload
        :action="''"
        :header="uploadHeader"
        :form-data="formData"
        :beforeUpload="beforeUpload"
        @success="$emit('success', $event)"
        @error="$emit('error', $event)"
        @progress="$emit('progress', $event)"
        :customBtn="true"
        :maxCount="maxCount"
        :fileList="fileList"
        @update:file-list="$emit('update:file-list', $event)"
    >
        <template #addBtn>
            <view class="custom-upload-box">
                <image :src="defaultBg" mode="aspectFill" class="custom-upload-image" />
            </view>
        </template>
    </u-upload>
</template>

<script setup lang="ts">
import { uploadImage } from '@/api/app'
import { defineProps, defineEmits, ref, computed } from 'vue'
import { useUserStore } from '@/stores/user'

const props = defineProps<{
    fileList?: any[]
    maxCount?: number
    category?: string
}>()

const emit = defineEmits(['success', 'error', 'progress', 'update:file-list'])
const userStore = useUserStore()

const uploadHeader = {
    token: userStore.token
}
const formData = computed(() => ({
    category: props.category ?? 'driver'
}))

const defaultBg = '../../static/images/upload_bg.png'
const isLoading = ref(false)
const isUploading = ref(false)
const beforeUpload = (file: any, lists: any[]) => {
    if (isUploading.value) {
      return false
    }
    isUploading.value = true
    uploadImageIng(lists).finally(() => {
        isUploading.value = false
    })
    // 可在此添加上传前校验逻辑
    return false
}

const uploadImageIng = async (filePath: any[]) => {
    try {
        isLoading.value = true
        uni.showLoading({
            title: '正在上传中...'
        })
        const results = []
        for (let i = 0; i < filePath.length; i++) {
            const result = await uploadImage(filePath[i].url)
            results.push(result.url)
            emit('progress', { progress: Math.floor(((i + 1) * 100) / filePath.length) })
        }
        emit('success', results)
    } catch (error) {
        emit('error', error)
        uni.showToast({ title: '上传失败', icon: 'none' })
    } finally {
        uni.hideLoading()
        isLoading.value = false
    }
}
</script>
<style lang="scss" scoped>
.custom-upload-box {
    width: 200px;
    height: 125px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    margin-left: auto; // 让盒子靠右
}

.custom-upload-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
}
</style>
